<?php
/**
 * This file is part of manage.
 * Author: tangzhou
 * Date: 2017/2/23
 * Time: 17:53
 * File: Vcc6015031601Controller.php
 */

namespace Ivr\HttpBundle\Controller;


use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use GuzzleHttp\Client;

class Vcc6015031601Controller extends Controller
{
    const CLIENT_ID = '10008';
    const CLIENT_SECRET = '7f62f9b47a45bc29a0061fec27d97dd7';
    const GRANT_TYPE = 'client_credentials';
    const ACCESS_URL = 'https://openapi.mafengwo.cn/oauth2/token';
    const USER_API_URL = 'https://openapi.mafengwo.cn/api/callcenter/send_sms';
    const GET_PHONE_NUM_URL = 'https://openapi.mafengwo.cn/api/callcenter/user_mobile?code=%s&access_token=%s&call_id=%s';
    const SEND_PUSH_CALL_RESULT = 'https://openapi.mafengwo.cn/api/callcenter/user_mobile/notify';

    public function indexAction(Request $request)
    {
        $key = $request->get('key', false);
        $phoneNum = $request->get('phone_num', '');
        if (!is_numeric($key) || empty($phoneNum)) {
            return new JsonResponse(array('result' => 'failure'));
        }

        $accessToken = $this->get('snc_redis.default')->get("6015031601.ACCESSTOKEN");
        if (empty($accessToken)) {
            //获取accessToken;
            $url = sprintf(
                "%s?grant_type=%s&client_id=%s&client_secret=%s",
                self::ACCESS_URL,
                self::GRANT_TYPE,
                self::CLIENT_ID,
                self::CLIENT_SECRET
            );
            $content = file_get_contents($url);
            if (!empty($content)) {
                $row = json_decode($content, true);
                if (json_last_error() !== JSON_ERROR_NONE || empty($row)) {
                    return new JsonResponse(array('result' => 'failure'));
                } else {
                    $accessToken = isset($row['access_token']) ? $row['access_token'] : '';
                    if (!empty($accessToken)) {
                        $this->get('snc_redis.default')->set("6015031601.ACCESSTOKEN", $accessToken);
                        $this->get('snc_redis.default')->expire("6015031601.ACCESSTOKEN", 7000);
                    } else {
                        return new JsonResponse(array('result' => 'failure'));
                    }
                }
            } else {
                return new JsonResponse(array('result' => 'failure'));
            }
        }

        //根据accesstoken去获取
        $userApiUrl = sprintf('%s?access_token=%s&phone_num=%s&code=%s&sAction=send_sms', self::USER_API_URL, $accessToken, $phoneNum, $key);
        $result = file_get_contents($userApiUrl);
        $resultArr = json_decode($result, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $this->get("logger")->error(sprintf('6015031601响应结果为非json格式，结果为【%s】.', $result));

            return new JsonResponse(array(
                'result' => 'failure',
            ));
        }
        if (empty($resultArr) || (isset($resultArr['result']) && $resultArr['result'] == 'error')) {
            return new JsonResponse(array(
                'result' => 'failure',
            ));
        }

        return new JsonResponse(array(
            'result' => 'success',
            'data' => array(
                'code' => '200',
            ),
        ));
    }

    /**
     * 获取号码
     * @param Request $request
     * @return JsonResponse
     */
    public function getPhoneNumAction(Request $request)
    {
        $code = $request->get('code',  '');
        $callId = $request->get('call_id',  '');
        if (empty($code)) {
            return new JsonResponse(array(
                'result' => 'failure',
            ));
        }
        if (empty($callId)) {
            return new JsonResponse(array(
                'result' => 'failure',
            ));
        }
        $token = $this->getAccessToken();
        if (empty($token)) {
            return new JsonResponse(array(
                'result' => 'failure',
            ));
        }
        //根据accesstoken去获取
        $phoneApiUrl = sprintf(self::GET_PHONE_NUM_URL, $code, $token, $callId);
        $result = file_get_contents($phoneApiUrl);
        $resultArr = json_decode($result, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $this->get("logger")->error(sprintf('6015031601-phone响应结果为非json格式，结果为【%s】.', $result));

            return new JsonResponse(array(
                'result' => 'failure',
            ));
        }
        if (empty($resultArr) || (isset($resultArr['result']) && $resultArr['result'] == 'failure') || !isset($resultArr['data']['phone_num'])) {
            return new JsonResponse(array(
                'result' => 'failure',
            ));
        }

        return new JsonResponse(array(
            'result' => 'success',
            'data' => array(
                'phone_num' => $resultArr['data']['phone_num'],
            ),
        ));
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function sendPushDataAction(Request $request)
    {
        try {
            $client = new Client(array(
                'timeout' => 5,
            ));
            $token = $this->getAccessToken();
            $headers = array(
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer '.$token,
            );
            $response = $client->post(self::SEND_PUSH_CALL_RESULT, array(
                'body' => $request->getContent(),
                'headers' => $headers,
            ));
            if ($response->getStatusCode() == 200) {
                $responseBody = $response->getBody()->getContents();
                $responseArray = json_decode($responseBody, true);
                if (json_last_error() == JSON_ERROR_NONE && isset($responseArray['code']) && $responseArray['code'] == 200) {
                    return new JsonResponse(array('code'=>200));
                } else {
                    $this->get('logger')->error(sprintf("马蜂窝呼叫结果推送失败非json或非200[%s]", $responseBody));

                    return new JsonResponse(array('code'=>202));
                }
            } else {
                $this->get('logger')->error(sprintf("马蜂窝呼叫结果推送失败code[%s]", $response->getStatusCode()));

                return new JsonResponse(array(
                    'code' => '201',
                ));
            }
        } catch (\Exception $e) {
            $this->get('logger')->error(sprintf("马蜂窝呼叫结果推送失败[%s]", $e->getMessage()));

            return new JsonResponse(array('code'=>203));
        }
    }

    /**
     * @return string
     */
    private function getAccessToken()
    {
        $accessToken = $this->get('snc_redis.default')->get("6015031601.ACCESSTOKEN");
        if (empty($accessToken)) {
            //获取accessToken;
            $url = sprintf(
                "%s?grant_type=%s&client_id=%s&client_secret=%s",
                self::ACCESS_URL,
                self::GRANT_TYPE,
                self::CLIENT_ID,
                self::CLIENT_SECRET
            );
            $content = file_get_contents($url);
            if (!empty($content)) {
                $row = json_decode($content, true);
                if (json_last_error() !== JSON_ERROR_NONE || empty($row)) {
                    return '';
                } else {
                    $accessToken = isset($row['access_token']) ? $row['access_token'] : '';
                    if (!empty($accessToken)) {
                        $this->get('snc_redis.default')->set("6015031601.ACCESSTOKEN", $accessToken);
                        $this->get('snc_redis.default')->expire("6015031601.ACCESSTOKEN", 7000);
                    } else {
                       return '';
                    }
                }
            } else {
                return '';
            }
        }

        return $accessToken;
    }

}
